import time
import math
import json

from django.shortcuts import render, render_to_response, get_object_or_404
from django.views.generic import ListView, DetailView
from microerp.apps.base.models import Users
from microerp.apps.base.views import *
from microerp.apps.finance.models import TransactionTable, TransactionLine


# 获取交易列表
def trans_list(request):
    if islogin(request):
        user = Users.objects.filter(id=get_user_id(request))[0]
        # query-----查询关键字
        # page------页码（每页10条数据）
        query = request.GET.get('query')
        page = request.GET.get('page', 1)
        # 得到交易列表数据
        if query:
            trans = TransactionTable.objects.filter(user=user).filter(
                memo__icontains=str(query)).order_by("-id")
            trans_list = trans[(page - 1) * 10:page * 10 - 1]
            totalRecords = trans.count()
        else:
            trans = TransactionTable.objects.filter(user=user).order_by("-id")
            trans_list = trans[(page - 1) * 10:page * 10 - 1]
            totalRecords = trans.count()

        # 开始获得分页数据
        totalPage = math.ceil(totalRecords / 10)
        return render(request, 'fim/trans_list.html', {'transations_table': trans_list, 'query': query, "totalPage": totalPage, "totalRecords": totalRecords})
    else:
        return render(request, 'base/signin.html')


class TransDetail(DetailView):
    """
    disply detial transation informaiton
    """

    model = TransactionTable
    context_object_name = 'transations_table'
    tempalte_name = "fim/trans_detail.html"


def  create_transations(request,   salesorder_id, purchaseorder_id):
    """
   1. 创建一条销售交易记录
        1.1 判断 变量   salesorder_id 是否为None， 如果不为None，准备插入记录，否则直接SKIP
        1.2 获取 SalesOrder 对象通过 PK =   salesorder_id， or id =  salesorder_id， 
        code：saleorder = SalesOrder.objects.get(pk=salesorder_id)
         1.3 获取所有关联到saleorder table的saleline对象
         saleline = saleorder.salesline_set.all()
        1.4 获取所关联到 saleline 的product 对象,一个line 对应一个product
        product =  Product.objects.get(saleline__id=saline.pk)
        1.5 获取每个porduct 的成本
        cost_price = product.cost
        1.6 计算line利润  (sale_price  - cost_price) * qty
        1.7 计算整个销售订单的利润    sum（line利润）-快递费用or其他额外支出
    """
